package com.zhentao.service.impl;


import com.zhentao.config.MinioConfig;
import com.zhentao.config.MinioConfigProperties;
import com.zhentao.service.FileStorageService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.UUID;

//@Service
@EnableConfigurationProperties(MinioConfigProperties.class)
@Import(MinioConfig.class)
@Service

public class FileStorageServiceImpl implements FileStorageService {
    @Resource
    private MinioConfigProperties minioConfigProperties;
    @Resource
    private MinioClient minioClient;
    @SneakyThrows
    @Override
    public String uploadHtmlFile(String fileName, InputStream inputStream) {
        String fname = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioConfigProperties.getBucket())
                .object(fname)
                .contentType("text/html")
                .stream(inputStream, inputStream.available(), -1)
                .build();
//        上传
        minioClient.putObject(putObjectArgs);

        String url = minioClient.getObjectUrl(putObjectArgs.bucket(), putObjectArgs.object());
        System.out.println(url);
        return url;
    }

    @SneakyThrows
    @Override
    public String uploadPicFile(String fileName, InputStream inputStream) {
//        minio上传文件
        String fname = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));

        PutObjectArgs poa = PutObjectArgs.builder()
                .bucket(minioConfigProperties.getBucket())
                .object(fname)
                .contentType("image/jpg")
                .stream(inputStream, inputStream.available(), -1)//
                .build();

//        上传
        minioClient.putObject(poa);

        String url = minioClient.getObjectUrl(poa.bucket(), poa.object());
        System.out.println(url);

        return url;
    }
}
